package com.easy.auth.controller;

import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.exception.ParameterException;
import com.easy.common.service.IRedisService;
import com.easy.common.service.IUserService;
import com.easy.common.util.JWTUtil;
import com.easy.common.util.PasswordDecode;
import com.easy.common.util.ResultData;
import com.easy.common.util.SYSUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("auth")
@CrossOrigin
public class AuthController {

    @DubboReference
    IUserService userService;
    @DubboReference
    IRedisService redisService;
    
    @PostMapping("login")
    public ResultData login(@RequestBody SysUser user){
        System.out.println(user);
        //获取用户名和密码
        String username= user.getUsername();
        String password= user.getPassword();
        if(SYSUtil.checkNotEmpty(username,password)){
            //获取用户名和数据
            //需要User模块的服务
            SysUser sysuser=userService.getByUsername(username);
            if (SYSUtil.checkNotNull(sysuser)){
                //比较密码
                String password_data=sysuser.getPassword();//数据中加密的密码
                if(PasswordDecode.decode(password,password_data)){
                    //如果成功就签发token
                    String token=JWTUtil.generateToken(null,null);
                    //认证成功，将token和新查询的SysUser数据存入redis
                    //提取权限和角色组成字符串存入redis
                    String allPermission=getAllpermission(sysuser);
                    redisService.set(token,allPermission);
                    return ResultData.success(token);
                }else{
                    throw new RuntimeException("密码不正确");
                }
            }else{
                throw new RuntimeException("没有此账号");
            }
        }else{
            throw new ParameterException("参数异常");
        }
    }
    public String getAllpermission(SysUser user){
        StringBuilder strb=new StringBuilder();
        for(SysRole role: user.getRole()){
            strb.append(role.getRolekey());
            strb.append(",");
            for(SysPermission permission : role.getPermissions()){
                strb.append(permission.getPermkey());
                strb.append(",");
            }
        }
        return strb.toString();
    }
}
